<template>
  <n-layout>
    <n-layout-header :bordered="true">
      <n-card :bordered="false" class="proCard" size="small">
        <BasicForm @register="register" @submit="handleSubmit"
                   @reset="handleReset">
        </BasicForm>
      </n-card>
    </n-layout-header>
    <n-layout-content>
      <n-grid cols="1 s:3 m:4 l:5 xl:7" responsive="screen">
        <n-grid-item span="1 m:2 l:3 xl:5">
          <!--          <n-card content-style="padding: 0;" :bordered="false">-->
          <div ref="chartRef" style="height:480px;width:100%;"></div>
          <!--          </n-card>-->
          <!--          style="width: 600px;height:480px;"-->
        </n-grid-item>
        <n-grid-item span="1 l:2">
          <n-space justify="space-between" align="end" style="padding:10px">
            <h6 style="font-weight: bold;font-size: large">新增用户</h6>
            <n-button type="info" @click="exportTable">新增明细导出</n-button>
          </n-space>
          <n-data-table
            id="nearlyTable"
            :remote="true"
            :columns="lastTableColumns"
            :loading="loaderRef"
            :data="dataRef"
            :bordered="false"
            :single-line="false"
            :single-column="true"
            :pagination="false"
            :max-height="400"
            :striped="true"
          />
        </n-grid-item>
      </n-grid>
    </n-layout-content>
  </n-layout>


</template>

<script lang="ts" setup>
import {useRouter} from 'vue-router';
import {onMounted, Ref, ref} from "vue";
import {FormSchema, useForm} from "@/components/Form";
import {useECharts} from "@/hooks/web/useECharts";
import {useMessage} from "naive-ui";
import {nearlyDays, nearlyDay, formatdate} from "@/utils/dateUtil";
import {getProjectList} from "@/api/statistics/stastistics";
import {utils, writeFileXLSX} from 'xlsx'
import {QueryParamsStore} from "@/store/modules/queryParamsCache";

const router = useRouter();
const message = useMessage();
// const height = basicProps.height;
// const width = basicProps.width;
const chartRef = ref<HTMLDivElement | null>(null);
const {setOptions, getInstance, echarts} = useECharts(chartRef as Ref<HTMLDivElement>);

const dataRef = ref([] as any)
const loaderRef = ref(true)

const queryParamsStore = QueryParamsStore();
const queryParams = ref(queryParamsStore.getColumnParams)
const queryDate = ref<[string, string]>([queryParams.value.begin, queryParams.value.end]);


const lastTableColumns = [
  {
    title: '日期',
    key: 'date',
    align: 'center',
  },
  {
    title: '激活IMEI',
    key: 'counts',
    align: 'center',
  },
]

const schemas = ref<FormSchema[]>([
    {
      field: 'project',
      labelMessage: '项目名称',
      component: 'NSelect',
      label: '项目',
      defaultValue: queryParams.value.project,
      componentProps: {
        placeholder: '请选择项目',
        filterable: true,
        options: [],
        onUpdateValue: (e: any) => {
          queryParams.value.project = e;
        },
      },
    },
    {
      field: 'region',
      label: '时间段',
      labelMessage: '时间段',
      component: "NRadioButtonGroup",
      defaultValue: queryParams.value.days,
      componentProps: {
        placeholder: '请选择最近日期',
        filterable: true,
        options: [
          {
            label: '近7天',
            value: 7,
          },
          {
            label: '近30天',
            value: 30,
          },
        ],
        onUpdateValue: (e: any) => {
          queryParams.value.days = e;
          queryDate.value[0] = nearlyDays(e);
          queryDate.value[1] = nearlyDays(1);
          queryParams.value.begin = queryDate.value[0];
          queryParams.value.end = queryDate.value[1];
          schemas.value[2].componentProps!['formattedValue'] = queryDate;
        },
      },
    },
    {
      field: 'dateRange',
      component: 'NDatePicker',
      label: '日期范围',
      componentProps: {
        placeholder: '请选择日期',
        type: 'daterange',
        formattedValue: queryDate,
        clearable: true,
        onUpdateValue: (e: any, formattedValue: string) => {
          if (formattedValue != null) {
            queryParams.value.begin = formattedValue[0];
            queryParams.value.end = formattedValue[1];
            queryDate.value[0] = formattedValue[0];
            queryDate.value[1] = formattedValue[1];
          }else {
            queryDate.value[0] = nearlyDays(queryParams.value.days);
            queryDate.value[1] = nearlyDays(1);
            queryParams.value.begin = queryDate.value[0];
            queryParams.value.end = queryDate.value[1];
          }
        },
        shortcuts:
          {
            '近7天': [new Date(nearlyDays(7)).getTime(), new Date(nearlyDays(1)).getTime()] as const,
            '近30天': [new Date(nearlyDays(30)).getTime(), new Date(nearlyDays(1)).getTime()] as const,
          }
      },
    },
  ])
;

const [register, {}] = useForm({
  gridProps: {
    // xGap: "5",
    // yGap: "8",
    cols: '1  m:1 l:3',
    // collapsed:true,
    collapsedRows: 3,
    // cols: '3'
  },
  // layout: 'horizontal',
  showAdvancedButton: false,
  showResetButton: false,
  labelWidth: 80,
  schemas,
});

setOptions({
  tooltip: {
    trigger: 'axis',
    show: true,
    /* formatter:(v)=>{
       console.log(v);
       return v;
     },*/
    axisPointer: {
      lineStyle: {
        width: 1,
        color: '#019680',
      },
    },
  },
  title: {
    text: '激活IMEI柱状图'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'top',
    data: ['激活数量']
  },
  grid: {left: '5%', right: '15%', top: '15%', bottom: '10%', containLabel: true},
  xAxis: {
    name: '日期(日)',
    type: 'category',
    splitNumber: queryParams.value.days,
    data: [],
    axisLabel: {
      interval: 0,
      color: (v) => {
        return (parseInt(formatdate(v)) % 2 == 0) ? 'CadetBlue' : 'black';
      },
      formatter: (v) => {
        return formatdate(v);
      },
    }
  },
  yAxis: {
    name: '激活数量',
    type: 'value',
    // max: 10000,
    splitNumber: 10,
  },
  series: [
    {
      name: '激活数量',
      data: [],
      type: 'bar',
      barMaxWidth: 80,
      label: {
        show: true,
        position: 'top',
        // rotate: 90,
        color: 'black',
        fontSize: 12,

      }
      /*showBackground: true,
      backgroundStyle: {
        color: 'rgba(220, 220, 220, 0.8)'
      }*/
    },
  ],
});

function fillDays(days = 7) {
  const titles = [] as any;
  for (let i = days; i > 0; i--) {
    titles.push(nearlyDay(i));
  }
  return titles;
}

onMounted(async () => {
  const projectList = await getProjectList();
  const projects = [] as any;
  projectList.forEach((e: any) => {
    projects.push({label: e['name'], value: e['id']});
  });
  schemas.value[0].componentProps!['options'] = projects;
  schemas.value[0].defaultValue = queryParams.value.project;
  await getLastDays();
});

async function getLastDays() {
  const barChar = getInstance();
  barChar?.showLoading();
  loaderRef.value = true;
  const {list} = await queryParamsStore.queryNearlyDays({...queryParams.value});
  dataRef.value = list;
  const titles = fillDays(queryParams.value.days);
  const count_list: number[] = new Array(queryParams.value.days);
  for (const {date, counts} of list) {
    const index = titles.indexOf(date);
    count_list[index] = counts;
  }
  console.log(count_list)
  setOptions({
    xAxis: {
      data: titles,
    },
    series: [
      {
        name: '激活数量',
        data: count_list,
      }
    ]
  }, false);
  barChar?.hideLoading();
  loaderRef.value = false;
}

function handleSubmit() {
  getLastDays();
}

function exportTable() {
  const workBook = utils.table_to_book(document.getElementById("nearlyTable"));
  try {
    writeFileXLSX(workBook, "新增用户明细.xlsx");
    message.success("导出成功");
  } catch (e) {
    message.error("导出失败");
  }
}

function handleReset(values: Recordable) {
}
</script>

<style lang="less" scoped>
.page-container {
  width: 100%;
  border-radius: 4px;
  padding: 50px 0;
  height: 100vh;

  .text-center {
    h1 {
      color: #666;
      padding: 20px 0;
    }
  }

  img {
    width: 350px;
    margin: 0 auto;
  }
}
</style>
